package c2.group.business.tb.boss;


import c2.advanced.business.base.KvData;
import c2.group.business.tb.TBSubModule;
import cate.common.table.d.GDThrone;
import cate.game.pvp.throne.msg.TBBossResultInnerReq;
import cate.game.role.RoleSimpleBase;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import easy.java.practice.errorcode.EcResult;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

@NoteClass("王座争霸-冠军boss")
public class TBBossModule extends TBSubModule {

	@NoteField("冠军boss基础数据")
	@Getter
	private TBBossStatus status;

	public void readFromBD() {
		status = useDb().kv.getByKey(KvData.KEY_TB_BOSS_BASE, TBBossStatus.class);
		if (status == null) {
			status = new TBBossStatus();
		}
		status.init(KvData.KEY_TB_BOSS_BASE);
	}

	public void save() {
		useDb().kv.save(status);
	}

	public void clear(){
		status.clear();
	}

	@Override
	public void onEnterNewSeason() {
		status.clear();
	}

	@Override
	public void onPeriodChange(byte period) {
		if (period != GDThrone.Period.CHAMPION_BOSS) {
			return;
		}
		RoleSimpleBase champion = parent.ko.getGroup(GDThrone.LevelGroup.G3).champion.match.getWinnerInfo();
		if (champion != null && !champion.isEmpty()) {
			status.setChampion(champion.uid);
		}
	}

	public EcResult<Void> challengeCheck(String roleUid, List<String> heroList) {
		EcResult<Void> r = new EcResult<>();
		if (!parent.getStatus().timeTable.inChampionBoss()) {
			return r.fail("挑战时间已过");
		}
		if (!StringUtils.equals(roleUid, status.championUid)) {
			return r.fail("仅有冠军可以挑战");
		}
		if (status.kill) {
			return r.fail("boss已被击杀");
		}
		for (String s : heroList) {
			if (status.heroUids.contains(s)) {
				return r.fail("无法使用重复英雄挑战");
			}
		}
		if (status.replays.size() >= useTable().tbBoss.champion.getFirst().challengeMax) {
			return r.fail("超过最大挑战次数");
		}
		return r.success();
	}

	public EcResult<Void> fightReport(TBBossResultInnerReq req) {
		EcResult<Void> r = new EcResult<>();
		if (!parent.getStatus().timeTable.inChampionBoss()) {
			return r.fail("挑战时间已过");
		}
		if (status.kill) {
			return r.fail("boss已被击杀");
		}
		status.kill = req.kill;
		status.hpExtend = req.hpExtend;
		status.heroUids.addAll(req.heroUids);
		status.replays.add(req.replay);
		if (req.kill) {
			status.totalKillTime++;
		}
		return r.success();
	}
}
